<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <title>编辑产品</title>
    <script type="text/javascript">
      Ext.onReady(function(){
        var gridHeight = 270;
        var id = new Ext.form.Hidden({
          name: 'id'
        });
        //单品或套装
        var isSuit = new Ext.form.RadioGroup({
          //width : 220,
          name: 'is_suit',
          fieldLabel: '套装',
          //hideLabel:true,
          //style:'margin-left:100px;margin-top:20px',
          columns : 2,
          anchor: '100%',
          vertical :false,
          items:[
            {boxLabel:'是',inputValue:1,name:'is_suit'},
            {boxLabel:'否',inputValue:0,name:'is_suit'}
          ]
        });

        isSuit.on("change",function(radioGroup,checkedRadio){
          if (isSuit.getValue().getGroupValue()==1){
            if (!productComponentsGrid.isVisible()){
              productComponentsGrid.setVisible(true);
              editProductWin.setHeight(editProductWin.getHeight() + gridHeight);
            }
          }else{
            productComponentsGrid.setVisible(false);
            editProductWin.setHeight(editProductWin.getHeight() - gridHeight);
          }
        })

        //为销售或组装
        var isSale = new Ext.form.RadioGroup({
          //width : 220,
          name: 'is_sale',
          fieldLabel: '销售',
          //hideLabel:true,
          //style:'margin-left:100px;margin-top:20px',
          columns : 2,
          anchor: '100%',
          vertical :false,
          items:[
            {boxLabel:'是',inputValue:1,name:'is_sale',checked:true},
            {boxLabel:'否',inputValue:0,name:'is_sale'}
          ]
        });

        //所有供应商
        var vendorTemplate = new Ext.XTemplate('<tpl for="."><div class="search-item">', '{name}', '</div></tpl>');
        var vendorStore = new Ext.data.Store({
          proxy: new Ext.data.HttpProxy({
            url: "/vendor/getAllVendors?for_cbb=true"
          }),
          reader: new Ext.data.JsonReader({
            root: 'root'
          }, [{
              name: 'id'
            }, {
              name: 'name'
            }])
        });

        //供应商
        var vendor = new Ext.form.ComboBox({
          store: vendorStore,
          fieldLabel: '供应商',
          allowBlank: false,
          blankText: "供应商必须选择",
          valueField: 'id',
          displayField: 'name',
          //name:'vendor_id',
          hiddenName: 'vendor_id',//如果不想提交displayField，则在这儿指定要提交的Key，value就是valueField．
          emptyText: '请选择...',
          editable:false,
          loadingText: '搜索中...',
          anchor: '97%',
          //pageSize: 10,
          //hideTrigger: false,
          readOnly:false,
          tpl: vendorTemplate,
          minChars: 0,
          itemSelector: 'div.search-item',
          triggerAction: 'all',
          editable:false,
          selectOnFocus:true
        });

        var number = new Ext.form.TextField({
          fieldLabel: '编号',
          allowBlank: false,
          blankText: "编号不能为空",
          name: 'number',
          anchor: '95%'
        });

        //品牌相关combobox
        var brandTemplate = new Ext.XTemplate('<tpl for="."><div class="search-item">', '{name}', '</div></tpl>');
        var brandStore = new Ext.data.Store({
          proxy: new Ext.data.HttpProxy({
            url: "/brand/getAllBrands?for_cbb=true"
          }),
          reader: new Ext.data.JsonReader({
            root: 'root'
          }, [{
              name: 'id'
            }, {
              name: 'name'
            }])
        });

        //品牌
        var brand = new Ext.form.ComboBox({
          store: brandStore,
          fieldLabel: '品牌',
          allowBlank: false,
          blankText: "品牌必须选择",
          valueField: 'id',
          displayField: 'name',
          hiddenName: 'brand_id',//如果不想提交displayField，则在这儿指定要提交的Key，value就是valueField．
          emptyText: '请选择...',
          editable:false,
          //typeAhead: false,
          loadingText: '搜索中...',
          anchor: '95%',
          readOnly:false,
          tpl: brandTemplate,
          minChars: 0,
          itemSelector: 'div.search-item',
          selectOnFocus:true
        });

        //产品类型相关combobox
        var productTypeTemplate = new Ext.XTemplate('<tpl for="."><div class="search-item">', '{name}', '</div></tpl>');
        var productTypeStore = new Ext.data.Store({
          proxy: new Ext.data.HttpProxy({
            url: "/product_type/getAllProductTypes?for_cbb=true"
          }),
          reader: new Ext.data.JsonReader({
            root: 'root'
          }, [{
              name: 'id'
            }, {
              name: 'name'
            }])
        });

        //产品
        var productType = new Ext.form.ComboBox({
          store: productTypeStore,
          fieldLabel: '产品类别',
          allowBlank: false,
          blankText: "类别必须选择",
          valueField: 'id',
          displayField: 'name',
          hiddenName: 'product_type_id',//如果不想提交displayField，则在这儿指定要提交的Key，value就是valueField．
          emptyText: '请选择...',
          editable:false,
          //typeAhead: false,
          loadingText: '搜索中...',
          anchor: '94%',
          readOnly:false,
          tpl: productTypeTemplate,
          minChars: 0,
          itemSelector: 'div.search-item',
          selectOnFocus:true
        });
        
        var name = new Ext.form.TextField({
          fieldLabel: '名称',
          allowBlank: false,
          blankText: "产品名称不能为空",
          name: 'name',
          anchor: '96%'
        });

        var spec = new Ext.form.TextField({
          fieldLabel: '规格',
          name: 'spec',
          anchor: '95%'
        });

        var unit = new Ext.form.TextField({
          fieldLabel: '单位',
          name: 'unit',
          anchor: '95%'
        });

        var unitPrice = new Ext.form.NumberField({
          fieldLabel: '销售单价',
          name: 'unit_price',
          allowBlank: false,
          allowDecimals: true,
          allowNegative: false,
          nanText:"您输入的不是数字",
          anchor: '95%'
        });

        var minQuantity = new Ext.form.NumberField({
          fieldLabel: '最少',
          name: 'min_quantity',
          allowBlank: false,
          allowDecimals: false,
          allowNegative: false,
          minValue: 0,
          maxValue: 10000,
          anchor: '95%'
        });

        var maxQuantity = new Ext.form.NumberField({
          fieldLabel: '最多',
          name: 'max_quantity',
          allowBlank: false,
          allowDecimals: false,
          allowNegative: false,
          minValue: 0,
          maxValue: 10000,
          anchor: '95%'
        });

        var costPrice = new Ext.form.NumberField({
          fieldLabel: '成本单价',
          name: 'cost_price',
          allowBlank: false,
          allowDecimals: true,
          allowNegative: false,
          decimalPrecision:10,
          minValue: 0,
          value:0,
          anchor: '95%'
        });

        var taxPrice = new Ext.form.NumberField({
          fieldLabel: '含税单价',
          name: 'tax_price',
          allowBlank: false,
          allowDecimals: true,
          allowNegative: false,
          decimalPrecision:10,
          minValue: 0,
          value:0,
          anchor: '95%'
        });
        
        var desc = new Ext.form.TextArea({
          fieldLabel: '描述',
          height:60,
          name: 'description',
          anchor: '97%'
        });

        //销售类型产品对应Grid
        var saleTypePricesDS = new Ext.data.Store({
          proxy: new Ext.data.HttpProxy({
            url: '/product/getPricesById?id=<%=@productId%>'
          }),
          reader: new Ext.data.JsonReader({
            totalProperty: 'totalProperty',
            root: 'root'
          }, [{
              name: 'id'
            },{
              name: 'name'
            }, {
              name: 'unit_price',
              type: 'float',
              convert:function(value,record){
                if(value == undefined || value == ''){
                  return -1;
                }else{
                  return value;
                }
              }
            },{
              name: 'product_price_id'
            }])
        });
        saleTypePricesDS.load();
        //销售类型产品价格对应Grid
        var saleTypePricesSM = new Ext.grid.CheckboxSelectionModel({singleSelect:true});
        var saleTypePricesCM = new Ext.grid.ColumnModel({defaults: {
            sortable: true,
            menuDisabled: false
          },columns:[new Ext.grid.RowNumberer(),saleTypePricesSM,
            {
              header: '销售类型',
              dataIndex: 'name',
              width: 190
            },{
              header: '单价',
              dataIndex: 'unit_price',
              align: 'right',
              renderer: Ext.util.Format.numberRenderer('0,000.00'),
              editor: new Ext.form.NumberField({
                allowBlank: false,
                allowDecimals: true,
                allowNegative: false
              }),
              width: 100
            }
          ]});

        //生成要订单的产品的Grid
        var saleTypePricesGrid = new Ext.grid.EditorGridPanel({
          store: saleTypePricesDS,
          cm: saleTypePricesCM,
          width: 350,
          height: 260,
          anchor: '100%',
          frame: true,
          title: '销售类型与产品价格列表',
          //frame: true,
          //plugins: checkColumn,
          clicksToEdit: 1//这里应该是单击就可以修改的意思。因为默认是要双击的。
        });
        
        //--------------------------------------------------------------------------
        var productTemplate = new Ext.XTemplate('<tpl for="."><div  class="search-item"><div style="float:left; width:230px">{name}</div><div>', '{is_suit}', '</div></div></tpl>');
        var productStore = new Ext.data.Store({
          proxy: new Ext.data.HttpProxy({
            url: "/product/getAllProducts"
          }),
          reader: new Ext.data.JsonReader({
            totalProperty: 'totalProperty',
            root: 'root'
          }, [{
              name: 'id'
            },{
              name: 'number'
            }, {
              name: 'name'
            }, {
              name: 'spec'
            }, {
              name: 'unit'
            }, {
              name: 'unit_price'
            }, {
              name: 'quantity'
            }, {
              name: 'description'
            }, {
              name: 'is_suit',
              convert:function(value,record){
                if(value == "1"){
                  return "套装";
                }else if(value == "0"){
                  return "单品";
                }
              }
            }])
        });
        //供应商产品
        var productCBB = new Ext.form.ComboBox({
          store: productStore,
          fieldLabel: '供应商产品',
          allowBlank: false,
          blankText: "产品必须选择",
          emptyText: '请选择...',
          //typeAhead: false,
          loadingText: '搜索中...',
          displayField: 'name',
          anchor: '95%',
          pageSize: 10,
          //hideTrigger: false,
          tpl: productTemplate,
          minChars: 0,
          itemSelector: 'div.search-item',
          selectOnFocus:true
        });

        productCBB.on('select', function(combo, record, index) {
          var subItemRecord = productComponentsSM.getSelected();
          if (!subItemRecord) {
            return false;
          }
          //Ext.MessageBox.alert("提示",rec.get('number'));
          subItemRecord.set('number',record.get('number'));
          subItemRecord.set('spec',record.get('spec'));
          subItemRecord.set('unit',record.get('unit'));
          subItemRecord.set('unit_price',record.get('unit_price'));
          subItemRecord.set('amount',record.get('unit_price'));
          subItemRecord.set('quantity',1);
          subItemRecord.set('discount',1.0);
          subItemRecord.set('product_id',record.get('id'));
          subItemRecord.set('is_suit',record.get('is_suit'));
        });

        //产品Grid Store
        var productComponentsDS = new Ext.data.Store({
          proxy: new Ext.data.HttpProxy({
            url: '/product/getAllComponentsById?id=<%=@productId%>'
          }),
          reader: new Ext.data.JsonReader({
            totalProperty: 'totalProperty',
            root: 'root'
          }, [{
              name: 'id'
            },{
              name: 'product_id',
              mapping:'component.id'
            } ,{
              name: 'number',
              mapping:'component.number'
            }, {
              name: 'product_name',
              mapping:'component.name'
            }, {
              name: 'description'
            }, {
              name: 'unit_price',
              mapping:'component.unit_price',
              type:'float'
            }, {
              name: 'quantity',
              type: 'int'
            }, {
              name: 'spec',
              mapping:'component.spec'
            }, {
              name: 'unit',
              mapping:'component.unit'
            },{
              name: 'is_suit',
              mapping:'component.is_suit',
              convert:function(value,record){
                if(value == "1"){
                  return "套装";
                }else if(value == "0"){
                  return "单品";
                }
              }
            }])
        });
        //生成产品Grid的CM
        var productComponentsSM = new Ext.grid.CheckboxSelectionModel({singleSelect:true});
        //var productComponentsSM = new Ext.grid.RowSelectionModel({singleSelect:true});
        var productComponentsCM = new Ext.grid.ColumnModel({defaults: {
            sortable: true,
            menuDisabled: false
          },columns:[new Ext.grid.RowNumberer(),productComponentsSM,
            {
              header: '产品名称',
              dataIndex: 'product_name',
              editor: productCBB,
              width: 290
            },{
              header: '产品ID',
              dataIndex: 'product_id',
              width: 50,
              hidden: false
            },{
              header: '产品编号',
              dataIndex: 'number',
              width: 95
            },{
              header: '规格',
              dataIndex: 'spec',
              width: 60
            },{
              header: '单位',
              dataIndex: 'unit',
              width: 60
            },{
              header: '数量',
              align: 'right',
              dataIndex: 'quantity',
              editor: new Ext.form.NumberField({
                allowBlank: false,
                allowDecimals: false,
                allowNegative: false
              }),
              width: 60
            },{
              header: '单价',
              dataIndex: 'unit_price',
              align: 'right',
              renderer: Ext.util.Format.numberRenderer('0,000.00'),
              width: 65
            },{
              header: '套装?',
              dataIndex: 'is_suit',
              width: 50
            }
          ]});

        //生成要订单的产品的Grid
        var productComponentsGrid = new Ext.grid.EditorGridPanel({
          store: productComponentsDS,
          cm: productComponentsCM,
          sm: productComponentsSM,
          width: 830,
          height: 270,
          loadMask: true,
          //frame: true,
          //title: '进货品种列表',
          //frame: true,
          //plugins: checkColumn,
          clicksToEdit: 1,//这里应该是单击就可以修改的意思。因为默认是要双击的。
          tbar: [{
              text: '添加产品',
              iconCls: 'addItem',
              handler : function(){
                // access the Record constructor through the grid's store
                var Product = productComponentsGrid.getStore().recordType;
                var record = new Product({
                  product_name: '请选择产品'
                });
                productComponentsGrid.stopEditing();
                productComponentsDS.insert(0, record);
                productComponentsGrid.startEditing(0, 0);
              }
            },{
              text: '删除',
              iconCls: 'remove',
              handler : function(){                
                var record = productComponentsSM.getSelected();
                if (!record) {
                  return false;
                }
                productComponentsDS.remove(record);
              }
            }]
        });        
        
        //暂时保存按钮
        var submitButton = new Ext.Button({
          text: '提交',
          tooltip: '保存产品信息。',
          iconCls: 'icon-save',
          handler: function(){
            if (vendor.getRawValue() === vendor.getValue()){
              vendor.reset();
            }
            if (productComponentsFormPanel.form.isValid()) {
              var allJsonStr = productComponentsFormPanel.getForm().getValues();
              allJsonStr = Ext.util.JSON.encode(allJsonStr);
              allJsonStr = Ext.util.Format.substr(allJsonStr,0,allJsonStr.length-1);

              var pricesJsonStr = gridStoreToJson(saleTypePricesDS);
              allJsonStr = allJsonStr + ",\"prices\":" + pricesJsonStr;
              
              //只有套装产品，才有附属产品
              if (isSuit.getValue().getGroupValue()==1){
                var productsJsonStr = gridStoreToJson(productComponentsDS,rejectKeyArray);
                if (productComponentsDS.getCount() == 0 || productsJsonStr === ""){
                  Ext.MessageBox.show({
                    title: '提示',
                    msg: "您还没有选择有效的产品或选择的产品数量为0！",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.INFO
                  });
                  return;
                }
                allJsonStr = allJsonStr + ",\"products\":" + productsJsonStr + "}";
              }else{
                allJsonStr = allJsonStr + "}";
              }
            
              this.disable();
              Ext.Ajax.request({
                url : '/product/update',
                success : function (result, request) {
                  if (Ext.util.JSON.decode(result.responseText).info.indexOf("成功") > -1) {
                    Ext.MessageBox.show({
                      title: '消息',
                      msg: "更新产品信息，操作成功！",
                      buttons: Ext.MessageBox.OK,
                      icon: Ext.MessageBox.INFO
                    });
                    editProductWin.destroy();
                  } else if (Ext.util.JSON.decode(result.responseText).info.indexOf("相同") > -1) {
                    Ext.MessageBox.show({
                      title: '消息',
                      msg: Ext.util.JSON.decode(result.responseText).info,
                      buttons: Ext.MessageBox.OK,
                      icon: Ext.MessageBox.WARNING
                    });
                    submitButton.enable();
                  } else {
                    Ext.MessageBox.show({
                      title: '消息',
                      msg: Ext.util.JSON.decode(result.responseText).info,
                      buttons: Ext.MessageBox.OK,
                      icon: Ext.MessageBox.WARNING
                    });
                    editProductWin.destroy();
                  }
                },
                failure : function (result, request){
                  Ext.MessageBox.show({
                    title: '消息',
                    msg: "通讯失败，请从新操作",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.WARNING
                  });
                  editProductWin.destroy();
                },
                method : 'POST',
                params : {
                  data : Ext.util.JSON.encode(allJsonStr),
                  authenticity_token: authToken.getValue()
                }
              });
            }
          }
        });

        //暂时保存按钮
        var closeButton = new Ext.Button({
          text: '关闭',
          tooltip: '关闭当前窗口，并且当前编辑的信息不能保存。',
          iconCls: 'exit',
          handler: function(){
            editProductWin.destroy();
          }
        });
        
        var productComponentsFormPanel = new Ext.form.FormPanel({
          //baseCls: 'x-plain',
          //renderTo: 'edit_product',
          labelWidth: 60,
          width: '850',
          labelAlign: 'right',
          frame : true,
          url: '/product/update',
          method: 'GET',
          reader: new Ext.data.JsonReader({
            root: 'root'
          }, [{
              name: 'id'
            }, {
              name: 'vendor_id'
            }, {
              name: 'number'
            }, {
              name: 'name'
            }, {
              name: 'spec'
            }, {
              name: 'unit'
            }, {
              name: 'unit_price'
            }, {
              name: 'min_quantity'
            }, {
              name: 'max_quantity'
            }, {
              name: 'brand_id'
            }, {
              name: 'product_type_id'
            }, {
              name: 'is_suit'
            }, {
              name: 'is_sale'
            }, {
              name: 'description'
            }]),
          //defaultType: 'textfield',
          items: [{
              layout:'column',
              items:[{
                  columnWidth:.5,
                  layout: 'form',
                  items: [vendor, name,{
                      layout: 'column',
                      items: [{
                          columnWidth:.5,
                          layout: 'form',
                          items: [isSuit]
                        },{
                          columnWidth:.5,
                          layout: 'form',
                          items: [isSale]
                        }]
                    },{
                      layout: 'column',
                      items: [{
                          columnWidth:.5,
                          layout: 'form',
                          items: [productType]
                        },{
                          columnWidth:.5,
                          layout: 'form',
                          items: [brand]
                        }]
                    },{
                      layout: 'column',
                      items: [{
                          columnWidth:.5,
                          layout: 'form',
                          items: [unit]
                        },{
                          columnWidth:.5,
                          layout: 'form',
                          items: [unitPrice]
                        }]
                    },{
                      layout: 'column',
                      items: [{
                          columnWidth:.5,
                          layout: 'form',
                          items: [number]
                        },{
                          columnWidth:.5,
                          layout: 'form',
                          items: [spec]
                        }]
                    },{
                      layout: 'column',
                      items: [{
                          columnWidth:.5,
                          layout: 'form',
                          items: [minQuantity]
                        },{
                          columnWidth:.5,
                          layout: 'form',
                          items: [maxQuantity]
                        }]
                    },{
                      layout: 'column',
                      items: [{
                          columnWidth:.5,
                          layout: 'form',
                          items: [costPrice]
                        },{
                          columnWidth:.5,
                          layout: 'form',
                          items: [taxPrice]
                        }]
                    },desc]
                },{
                  columnWidth:.5,
                  layout: 'form',
                  items: [saleTypePricesGrid]
                }]
            },productComponentsGrid,id],
          buttons: [submitButton,closeButton]
        });
        productComponentsFormPanel.render('edit_product');
        //
        //productComponentsGrid.on('afteredit', afterEdit, this );        

        function afterEdit(obj) {
          // execute an XHR to send/commit data to the server, in callback do (if successful):
          if(obj.field=="quantity"||obj.field=="unit_price"||obj.field=="discount"){
            if(obj.record.get('quantity')>0 && obj.record.get('unit_price') >0){
              obj.record.set('amount',obj.record.get('quantity')*10000*obj.record.get('unit_price')*obj.record.get('discount')/10000);
            }else{
              obj.record.set('amount',0);
            }
          }
        }


        productComponentsFormPanel.form.load({
          url: '/product/edit?id=' + <%=@productId%>,
          method : 'GET',
          waitMsg: '正在载入数据...',
          success: function(form, action){
            var respJson = Ext.util.JSON.decode(action.response.responseText);
            vendor.setRawValue(respJson.root[0].vendor.name);
            brand.setRawValue(respJson.root[0].brand.name);
            if (respJson.root[0].product_type != null){
              productType.setRawValue(respJson.root[0].product_type.name);
            }

            productComponentsDS.load();
          },
          failure: function(form, action){
            Ext.MessageBox.alert('提示信息', '信息加载失败');
          }
        });

      })
    </script>
  </head>
  <body>
    <div id="edit_product"></div>
  </body>
</html>